<?php
require_once('kernel.inc');
require_once(LIBRARIES.'/image.class.inc');

$img     = false;
$image   = false;
$images  = false;
$uploads = array();

if($AUTH->logedstatus === true && $AUTH->permission == 'system')
{
   $upload_path = ROOT . $MECCANO->system['images'] . '/upload';
   // SESSION HANDLER FOR GALLERY
   if($category !== false) $_SESSION['gallery']['category'] = $category;
   if(isset($_SESSION['gallery']['category'])) $category = $_SESSION['gallery']['category'];
   if($moduleid !== false) $_SESSION['gallery']['moduleid'] = $moduleid;
   if(isset($_SESSION['gallery']['moduleid'])) $moduleid = $_SESSION['gallery']['moduleid'];


   switch($event)
   {
      case 14:
         if($submit)
         {
            
            if(isset($_FILES['image'])  && $_FILES['image']['name'] != '')
            {
               
               $image = uploadfile($_FILES['image']['name'], $upload_path, $_FILES['image']['tmp_name']);
               if($image)
               {
                  $path = $upload_path . '/' . $image;
                  $path_i1 = $upload_path . '/i1_' . $image;
                  $path_i2 = $upload_path . '/i2_' . $image;
                  $path_i3 = $upload_path . '/i3_' . $image;
                  $IM = new Image();
                  $params = 'w='.$MECCANO->system['gal_sw'].';h='.$MECCANO->system['gal_sh'].';l=1';
                  $IM->SetParams($params);
                  $img[0] = $IM->Resize($path, $path_i1);
                  $img[0]['file'] = 'i1_' . $image;
                  $params = 'w='.$MECCANO->system['gal_mw'].';h='.$MECCANO->system['gal_mh'].';l=1';
                  $IM->SetParams($params);
                  $img[1] = $IM->Resize($path, $path_i2);
                  $img[1]['file'] = 'i2_' . $image;
                  $params = 'w='.$MECCANO->system['gal_lw'].';h='.$MECCANO->system['gal_lh'].';l=1';
                  $IM->SetParams($params);
                  $img[2] = $IM->Resize($path, $path_i3);
                  $img[2]['file'] = 'i3_' . $image;
                  if($img)
                  {
                     $img['m'] = $moduleid;
                     if(file_exists($upload_path . '/uploads'))
                     {
                        $fp = fopen($upload_path . '/uploads', 'r');
                        $uploads = fread($fp, filesize($upload_path . '/uploads'));
                        fclose($fp);
                        $uploads = unserialize($uploads);
                        $uploads[count($uploads)] = $img;
                     } else
                     {
                        $uploads[] = $img;
                     }
                     $uploads = serialize($uploads);
                     $fp = fopen($upload_path . '/uploads', 'w');
                     fwrite($fp, $uploads);
                     fclose($fp);
                     unlink($path);
                     $make = true;
                  }
               } else
               {
                  $error = true;
               }
            }
         }
         
         $max_upload_size = min(let_to_num(ini_get('post_max_size')), let_to_num(ini_get('upload_max_filesize')));
         RoundSizeBites($max_upload_size);
         $SMARTY->assign('max_upload_size', $max_upload_size);
         $SMARTY->display('admin.addimage.tpl.html', $_SYS['meccano']['pid']);
         break;
         
      case 15:
         if(file_exists($upload_path . '/uploads'))
         {
            $fp = fopen($upload_path . '/uploads', 'r');
            $images = fread($fp, filesize($upload_path . '/uploads'));
            fclose($fp);
            $images = unserialize($images);

         }

         $key = isset($_REQUEST['key']) ? isDigit($_REQUEST['key']) : false;
         if($submit && $key !== false && isset($images[$key]))
         {
            $proc_img = $images[$key];
            unset($images[$key]);
            if($MECCANO->system['gal_sp'] == 1)
            {
               $proc_img[0]['n_w'] = $MECCANO->system['gal_sw'];
               $proc_img[0]['n_h'] = $MECCANO->system['gal_sh'];
            } else
            {
               $proc_img[0]['n_w'] = isset($_REQUEST['nsw']) ? isDigit($_REQUEST['nsw']) : $MECCANO->system['gal_sw'];
               $proc_img[0]['n_h'] = isset($_REQUEST['nsh']) ? isDigit($_REQUEST['nsh']) : $MECCANO->system['gal_sh'];
            }
            $proc_img[0]['x']    = isset($_REQUEST['sX'])  ? isDigit($_REQUEST['sX'])  : 0;
            $proc_img[0]['y']    = isset($_REQUEST['sY'])  ? isDigit($_REQUEST['sY'])  : 0;
            $proc_img[0]['dest'] = ROOT . $MECCANO->system['images'] . '/small';
            $proc_img[0]['source'] = ROOT . $MECCANO->system['images'] . '/upload';
            if($MECCANO->system['gal_mp'] == 1)
            {
               $proc_img[1]['n_w'] = $MECCANO->system['gal_mw'];
               $proc_img[1]['n_h'] = $MECCANO->system['gal_mh'];
            } else
            {
               $proc_img[1]['n_w'] = isset($_REQUEST['nmw']) ? isDigit($_REQUEST['nmw']) : $MECCANO->system['gal_mw'];
               $proc_img[1]['n_h'] = isset($_REQUEST['nmh']) ? isDigit($_REQUEST['nmh']) : $MECCANO->system['gal_mh'];
            }
            $proc_img[1]['x']    = isset($_REQUEST['mX'])  ? isDigit($_REQUEST['mX'])  : 0;
            $proc_img[1]['y']    = isset($_REQUEST['mY'])  ? isDigit($_REQUEST['mY'])  : 0;
            $proc_img[1]['dest'] = ROOT . $MECCANO->system['images'] . '/mid';
            $proc_img[1]['source'] = ROOT . $MECCANO->system['images'] . '/upload';
            if($MECCANO->system['gal_lp'] == 1)
            {
               $proc_img[2]['n_w'] = $MECCANO->system['gal_lw'];
               $proc_img[2]['n_h'] = $MECCANO->system['gal_lh'];
            } else
            {
               $proc_img[2]['n_w'] = isset($_REQUEST['nlw']) ? isDigit($_REQUEST['nlw']) : $MECCANO->system['gal_lw'];
               $proc_img[2]['n_h'] = isset($_REQUEST['nlh']) ? isDigit($_REQUEST['nlh']) : $MECCANO->system['gal_lh'];
            }
            $proc_img[2]['x']    = isset($_REQUEST['lX'])  ? isDigit($_REQUEST['lX'])  : 0;
            $proc_img[2]['y']    = isset($_REQUEST['lY'])  ? isDigit($_REQUEST['lY'])  : 0;
            $proc_img[2]['dest'] = ROOT . $MECCANO->system['images'] . '/large';
            $proc_img[2]['source'] = ROOT . $MECCANO->system['images'] . '/upload';

            foreach($proc_img AS $file)
            {
               ResizeImage($file);
            }
            
            $prim_key = $MECCANO->GetTableKey('meccano_images');

            for($i=0,$t=count($MECCANO->system['lang']); $i<$t; $i++)
            {
               $DB->DB_QueryBuilder('INSERT INTO meccano_images (
                  id,
                  lang,
                  mid,
                  cat,
                  title,
                  description,
                  s_file,
                  s_w,
                  s_h,
                  m_file,
                  m_w,
                  m_h,
                  l_file,
                  l_w,
                  l_h)
                  VALUES (
                  '.$prim_key.',
                  "'.$MECCANO->system['lang'][$i].'",
                  '.$moduleid.',
                  '.$category.',
                  "%s", 
                  "%s", 
                  "%s", 
                  %i, 
                  %i, 
                  "%s", 
                  %i, 
                  %i, 
                  "%s", 
                  %i, 
                  %i)',
               array(
                  $_POST['title'][$MECCANO->system['lang'][$i]],
                  $_POST['descr'][$MECCANO->system['lang'][$i]],
                  $proc_img[0]['file'],
                  $proc_img[0]['n_w'],
                  $proc_img[0]['n_h'],
                  $proc_img[1]['file'],
                  $proc_img[1]['n_w'],
                  $proc_img[1]['n_h'],
                  $proc_img[2]['file'],
                  $proc_img[2]['n_w'],
                  $proc_img[2]['n_h']
               ));
               $DB->DB_Query();
               $make = true;
            }
            unlink($upload_path . '/uploads');
            if(count($images) > 0)
            {
               $images = array_values($images);
               $uploads = serialize($images);
               $fp = fopen($upload_path . '/uploads', 'w');
               fwrite($fp, $uploads);
               fclose($fp);
            }
         }

         if($images != false && count($images) > 0) foreach($images AS $key=>$image)
         {
            if($image['m'] == $moduleid)
            {
               $image['key'] = $key;
               break;
            }
         }
         
         $SMARTY->assign('image', $image);
         
         $SMARTY->display('admin.editimage.tpl.html', $_SYS['meccano']['pid']);
         break;
         
      case 16:
         if(isset($_REQUEST['del_img']))
         {
            $del = array_filter($_REQUEST['del_img'], 'isDigit');
            $del = implode(',', $del);
            $DB->sql = 'SELECT * FROM meccano_images WHERE id IN (' . $del . ')';
            $DB->DB_Fetch();
            for($i=0,$t=$DB->rows; $i<$t; $i++)
            {
               @unlink(ROOT . $MECCANO->system['images'] . '/small/' . $DB->fetched[$i]['s_file']);
               @unlink(ROOT . $MECCANO->system['images'] . '/mid/' . $DB->fetched[$i]['m_file']);
               @unlink(ROOT . $MECCANO->system['images'] . '/large/' . $DB->fetched[$i]['l_file']);
            }
            $DB->sql = 'DELETE FROM meccano_images WHERE id IN (' . $del . ')';
            $DB->DB_Query();
         }
            
      default:
         $GALLERY = new kernel($moduleid);
         $images = $GALLERY->Images($category);
         $SMARTY->assign('images', $images);
         $SMARTY->display('admin.images.tpl.html', $_SYS['meccano']['pid']);
   }
} else
{
   echo $AUTH->frame_redirector();
}



function let_to_num($v)
{
   $l = substr($v, -1);
   $ret = substr($v, 0, -1);
   switch(strtoupper($l))
   {
      case 'P':
         $ret *= 1024;
      case 'T':
         $ret *= 1024;
      case 'G':
         $ret *= 1024;
      case 'M':
         $ret *= 1024;
      case 'K':
         $ret *= 1024;
         break;
   }
   return $ret;
}

function ResizeImage($file)
{
   if($file['width'] != $file['n_w'] || $file['height'] != $file['n_h'])
   {
      $filename = MoveFile($file['source'].'/'.$file['file'], $file['dest'].'/'.$file['file'], 'PN');
      $exec_str = 'convert '.$file['source'].'/'.$file['file'].' -crop '.$file['n_w'].'x'.$file['n_h'].'+'.$file['x'].'+'.$file['y'].' '.$file['dest'].'/'.$file['file'];
      exec($exec_str);
      @unlink($file['source'].'/'.$file['file']);
   }
   else
   {
      MoveFile($file['source'].'/'.$file['file'], $file['dest'].'/'.$file['file']);
   }
}